﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MS.InformationManagement.DAL.DocumentCenter;
using Microsoft.SharePoint;
using MS.InformationManagement.Support;

namespace MS.InformationManagement.BLL.informedDocument
{
    public class InformedDocument
    {

        public string GetRadicadoUrl(int requestId)
        {
            using (var dc = new DCDocumentCenterDataContext(SPContext.Current.Web.Url))
            { 
                string userLibrary = SPContext.Current.Web.CurrentUser.LoginName.GetUserWithOutDomain();
                string result = string.Empty;
                var radicado = (from solicitud in dc.GetList<SolicitudInformar>(userLibrary)
                                where solicitud.Id == requestId
                                select solicitud).FirstOrDefault();
                result = radicado.URL.GetEntityFieldUrl();
                if(!documentExists(result))
                    throw new Exception(string.Format("El radicado {0} ha sido reasignado o movido de su ubicación actual",radicado.NoRadicado));
                return result;
            }
        }

        private bool documentExists(string informedUrl)
        {
            bool result = false;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite currentSite = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb currentWeb = currentSite.OpenWeb())
                    {
                        string itemId = getQueryStringValue(informedUrl, "ID");
                        Guid listId = new Guid(getQueryStringValue(informedUrl, "ListId"));
                        SPList targetList = currentWeb.Lists.GetList(listId, false);
                        SPQuery documentQuery = new SPQuery();
                        documentQuery.Query = string.Format("<Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>{0}</Value></Eq></Where>",itemId);
                        documentQuery.ViewFields = "<FieldRef Name='ID'></FieldRef>";
                        var items = targetList.GetItems(documentQuery);
                        result = items.Count == 0 ? false : true;
                    }
                }
            });
            return result;
        }


        private string getQueryStringValue(string url,string keyName)
        {
            var parameters = url.Split('?');

            if(parameters.Count() < 2)
                return string.Empty;

            var keys = parameters[1].Split('&');

            if (keys.Count() <= 1)
                return string.Empty;

            var keyValue = (from key in keys
                            from nameKey in key.Split('=')
                            where nameKey.ToLower() == keyName.ToLower()
                            select key).FirstOrDefault();

            if (keyValue == null)
                return string.Empty;

            return keyValue.Split('=')[1];        
        }

    }
}
